package com.hos.db.manager;

import com.hos.db.create.relation.RelationTable;
import com.hos.db.create.user.UserDocTable;
import com.hos.db.create.user.UserPatTable;
import com.hos.db.entity.UserDocEntity;
import com.hos.db.entity.UserPatsEntity;
import com.hos.db.entity.relation.RelationEntity;
import com.hos.net.res.BaseResponse;
import com.hos.net.res.MsgHint;
import com.hos.utile.DLog;
import com.hos.utile.DateUtile;
import com.hos.utile.JsonUtile;
import com.hos.utile.Md5Utile;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;

import java.util.Date;
import java.util.List;

//关系
public class RelationManager {

    private static RelationManager userPatsManager;

    public static RelationManager getInstance() {
        if (userPatsManager == null) {
            userPatsManager = new RelationManager();
        }
        return userPatsManager;
    }

    //查询关系状态
    public RelationEntity onQuery(JdbcTemplate jdbcTemplate, String docId, String patId) {
        //SELECT column_name,column_name FROM table_name [WHERE Clause] [LIMIT N][ OFFSET M]

        String sql = "SELECT * FROM " + RelationTable.tableName
                + " WHERE "
                + RelationTable.tableDocId + " = '" + docId + "'"
                + " AND "
                + RelationTable.tablePatId + " = '" + patId + "'";
        DLog.e("sql:" + sql);
        RelationEntity entity = null;
        List<RelationEntity> entitys = onQuery(jdbcTemplate, sql);
        if (entitys != null && entitys.size() > 0) {
            entity = entitys.get(0);
        }
        return entity;
    }

    //添加
    public String onRelationAddReq(JdbcTemplate jdbcTemplate, String docId, String patId) {
        String response = new MsgHint("添加失败").toJson();
        String id = Md5Utile.encode(docId + patId);
        String sql = "SELECT * FROM " + RelationTable.tableName
                + " WHERE "
                + RelationTable.tableRelationId + " = '" + id + "'";
        List<RelationEntity> list = onQuery(jdbcTemplate, sql);
        if (list != null && list.size() > 0) {
            return new MsgHint("关系存在").toJson();
        }
        sql = "INSERT INTO " + RelationTable.tableName
                + "("
                + RelationTable.tableRelationId + ","
                + RelationTable.tableDocId + ","
                + RelationTable.tablePatId + ","
                + RelationTable.tableRelationCreateTime + ","
                + RelationTable.tableRelationUpdateTime
                + ")"
                + " VALUES (?,?,?, ?, ?)";

        try {
            Date time = new Date();

            int status = jdbcTemplate.update(sql,
                    new Object[]{id, docId, patId, time, time});
            if (status > 0) {
                RelationEntity data = new RelationEntity();
                data.setDocId(docId);
                data.setPatId(patId);
                data.setRelationId(id);
                data.setRelationCreateTime(time);
                BaseResponse res = new BaseResponse();
                res.obj = data;
                response = res.toJson("0", "关注成功");
            }
        } catch (Exception e) {
            DLog.e("添加失败：" + e.getMessage());
        }
        return response;
    }

    //删除
    public String onRelationDeleteReq(JdbcTemplate jdbcTemplate, String relationId) {

        String sql = "DELETE  FROM " + RelationTable.tableName
                + " WHERE "
                + RelationTable.tableRelationId + " = '" + relationId + "'";
        int state = jdbcTemplate.update(sql);
        if (state == 0) {
            return new MsgHint("关系不存在").toJson();
        }
        return new MsgHint("0", "删除成功").toJson();
    }

    /**
     * 更新备注
     *
     * @param jdbcTemplate
     * @return
     */
    public String onUpdateRemark(JdbcTemplate jdbcTemplate, String relationId, String remark,
                                 List<String> imgs) {
        String where = RelationTable.tablePatRemark + " = '" + remark + "' , ";
        if (imgs != null && imgs.size() > 0) {
            where += RelationTable.tablePatRemarkImages + " = '" + JsonUtile.obj2Json(imgs) + "' , ";
        } else {
            where += RelationTable.tablePatRemarkImages + " = '" + "" + "' , ";
        }
        String sql = "UPDATE " + RelationTable.tableName
                + " SET "
                + where
                + RelationTable.tableRelationUpdateTime + " = '"
                + DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS) + "'"
                + " WHERE "
                + RelationTable.tableRelationId + " = '" + relationId + "'";
        int j = jdbcTemplate.update(sql);
        if (j > 0) {
            return new MsgHint("0", "更新成功").toJson();
        }
        return new MsgHint("关系不存在").toJson();
    }

    /**
     * 患者获取医生
     *
     * @param jdbcTemplate
     * @param pageNo       页面（>=1）
     * @param pageSize     每页查询数量
     */
    public List<UserDocEntity> onDocs(JdbcTemplate jdbcTemplate, String patId,
                                      int pageNo, int pageSize, boolean hasNextPage) {
        int next = 0;
        if (hasNextPage) {
            next = 1;
        }
        String sql = "SELECT "
                + "r." + RelationTable.tableRelationId
                + " ,r." + RelationTable.tableDocRemark
                + " ,d." + UserDocTable.tableDocId
                + " ,d." + UserDocTable.tableDocName
                + " ,d." + UserDocTable.tableDocPhone
                + " ,d." + UserDocTable.tableDocPortrait
                + " ,d." + UserDocTable.tableDocPower
                + " ,d." + UserDocTable.tableDocTitle
                + " ,d." + UserDocTable.tableDocHosName
                + " ,d." + UserDocTable.tableDocDeptName
                + " from "
                + RelationTable.tableName + " r "
                + " LEFT OUTER JOIN  "
                + UserDocTable.tableName + " d "
                + " on "
                + "r." + RelationTable.tableDocId
                + " = "
                + "d." + UserDocTable.tableDocId
                + " WHERE "
                + "r." + RelationTable.tablePatId + " = '" + patId + "'"
                + " limit "
                + (pageNo - 1) * pageSize + " , " + (pageSize + next);
        List<UserDocEntity> dcos = jdbcTemplate.query(sql,
                ParameterizedBeanPropertyRowMapper.newInstance(UserDocEntity.class));

        return dcos;
    }

    /**
     * 医生获取患者
     *
     * @param jdbcTemplate
     * @param pageNo       页面（>=1）
     * @param pageSize     每页查询数量
     */
    public List<UserPatsEntity> onPats(JdbcTemplate jdbcTemplate, String docId,
                                       int pageNo, int pageSize, boolean hasNextPage) {
        int next = 0;
        if (hasNextPage) {
            next = 1;
        }
        String sql = "SELECT "
                + "r." + RelationTable.tableRelationId
                + " ,r." + RelationTable.tablePatRemark
                + " ,r." + RelationTable.tablePatRemarkImages
                + " ,d." + UserPatTable.tablePatId
                + " ,d." + UserPatTable.tablePatName
                + " ,d." + UserPatTable.tablePatPhone
                + " ,d." + UserPatTable.tablePatPortrait
                + " ,d." + UserPatTable.tablePatAddress
                + " ,d." + UserPatTable.tablePatBirthday
                + " ,d." + UserPatTable.tablePatSex
                + " ,d." + UserPatTable.tablePatIdentityNumber
                + " from "
                + RelationTable.tableName + " r "
                + " LEFT OUTER JOIN  "
                + UserPatTable.tableName + " d "
                + " on "
                + "r." + RelationTable.tablePatId
                + " = "
                + "d." + UserPatTable.tablePatId
                + " WHERE "
                + "r." + RelationTable.tableDocId + " = '" + docId + "'"
                + " limit "
                + (pageNo - 1) * pageSize + " , " + (pageSize + next);
        List<UserPatsEntity> pats = jdbcTemplate.query(sql,
                ParameterizedBeanPropertyRowMapper.newInstance(UserPatsEntity.class));

        return pats;
    }

    //查询
    private List<RelationEntity> onQuery(JdbcTemplate jdbcTemplate, String sql) {
        List<RelationEntity> list = null;
        try {
            list = jdbcTemplate.query(sql,
                    ParameterizedBeanPropertyRowMapper.newInstance(RelationEntity.class));
            DLog.e("查询成功：==========");
        } catch (Exception e) {
            DLog.e("查询失败：" + e.getMessage());
        }
        return list;
    }

}
